package com.dims_hsrc.data.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.io.IOException;

@Service
public class LlmService {

    @Value("${llm.api.url}")
    private String apiUrl;

    @Value("${llm.api.key}")
    private String apiKey;
    
    // Maximum content length to send in a single request
    private static final int MAX_CONTENT_LENGTH = 15000;
    
    // Maximum request timeout (milliseconds)
    private static final int MAX_REQUEST_TIMEOUT = 300000; // 5 minutes
    
    // 模拟存储自定义标准的内存数据库
    private final Map<String, CustomStandard> customStandardsStorage = new HashMap<>();

    @PostConstruct
    public void init() {
        System.out.println("LLM服务初始化，API URL: " + apiUrl);
        System.out.println("API Key前缀: " + (apiKey != null && apiKey.length() > 4 ? apiKey.substring(0, 4) + "..." : "未设置"));
    }

    public List<Map<String, Object>> extractRequirements(String content) {
        if (content == null || content.isEmpty()) {
            throw new IllegalArgumentException("内容不能为空");
        }
        
        System.out.println("开始提取需求，内容长度: " + content.length());
        
        // For large content, split into chunks
        if (content.length() > MAX_CONTENT_LENGTH) {
            return processLargeContent(content);
        }

        try {
            Map<String, Object> requestBody = new HashMap<>();
            // 使用Moonshot的模型
            requestBody.put("model", "moonshot-v1-32k");

            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个专业的需求分析师，请从以下文档中提取关键的高速列车组成成分的需求。对每个需求，提供以下信息：1. 需求名称，2. 需求类型（文本text/数值num/选项option/范围range），并且对于需求：直接可以用文本描述的是text类型 对于需要熟悉公式描述的是num类型 有多个可能选项的是option类型 ");
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", content);

            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            
            // 添加温度等参数
            requestBody.put("temperature", 0.7);
            requestBody.put("top_p", 0.8);
            requestBody.put("stream", false);
            // 减少响应令牌数量以加快响应速度
            requestBody.put("max_tokens", 2000);

            System.out.println("请求体构建完成，开始调用API");
            ResponseEntity<String> response = callLlmApi(requestBody);
            System.out.println("API调用完成，解析响应");
            return parseResponse(response.getBody());
        } catch (ResourceAccessException e) {
            System.err.println("API连接超时或网络错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("API请求超时，文档可能过大，请尝试使用较小的文档或分段处理: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("提取需求过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("处理文档失败: " + e.getMessage());
        }
    }
    
    /**
     * Process large content by splitting into chunks
     */
    private List<Map<String, Object>> processLargeContent(String content) {
        System.out.println("文档内容过长 (" + content.length() + " 字符)，分块处理");
        List<Map<String, Object>> allRequirements = new ArrayList<>();
        
        // Simply get the first part of the document if it's too large
        // This is a simple approach - could be enhanced with more sophisticated chunking
        String truncatedContent = content.substring(0, Math.min(content.length(), MAX_CONTENT_LENGTH));
        
        try {
            System.out.println("处理第一部分内容，长度: " + truncatedContent.length());
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "moonshot-v1-32k");

            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个专业的需求分析师，请从以下文档中提取关键的高速列车组成成分的需求。对每个需求，提供以下信息：1. 需求名称，2. 需求类型（文本text/数值num/选项option/范围range），并且对于需求：直接可以用文本描述的是text类型 对于需要熟悉公式描述的是num类型 有多个可能选项的是option类型");

            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", truncatedContent);

            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            
            requestBody.put("temperature", 0.7);
            requestBody.put("top_p", 0.8);
            requestBody.put("stream", false);
            requestBody.put("max_tokens", 2000);

            System.out.println("第一部分请求体构建完成，开始调用API");
            ResponseEntity<String> response = callLlmApi(requestBody);
            System.out.println("第一部分API调用完成，解析响应");
            
            allRequirements.addAll(parseResponse(response.getBody()));
            
            return allRequirements;
        } catch (Exception e) {
            System.err.println("处理大文档时发生异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("处理大文档失败，请尝试上传较小的文档: " + e.getMessage());
        }
    }

    private ResponseEntity<String> callLlmApi(Map<String, Object> requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        // 创建RestTemplate并设置更长的超时时间
        RestTemplate restTemplate = new RestTemplate();
        
        // 设置更长的超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(MAX_REQUEST_TIMEOUT); 
        requestFactory.setReadTimeout(MAX_REQUEST_TIMEOUT);   
        restTemplate.setRequestFactory(requestFactory);
        
        // 验证API URL
        if (apiUrl == null || apiUrl.trim().isEmpty()) {
            throw new IllegalStateException("API URL未配置，请检查应用配置");
        }
        
        // 创建完整的API URL - 避免重复路径
        String chatCompletionsUrl = apiUrl;
        if (chatCompletionsUrl.endsWith("/v1/chat/completions")) {
            // URL已经包含了完整路径，不需要再添加
        } else {
            // 添加路径
            if (!chatCompletionsUrl.endsWith("/")) {
                chatCompletionsUrl += "/";
            }
            if (!chatCompletionsUrl.contains("/v1/chat/completions")) {
                chatCompletionsUrl += "v1/chat/completions";
            }
        }
        
        System.out.println("调用LLM API: " + chatCompletionsUrl);
        System.out.println("API Key前缀: " + (apiKey != null && apiKey.length() > 4 ? apiKey.substring(0, 4) + "..." : "未设置"));
        System.out.println("请求体大小: " + requestBody.toString().length() + " 字符");
        
        // 添加重试机制
        int maxRetries = 3;
        int retryCount = 0;
        long retryDelayMs = 2000; // 初始延迟2秒
        
        while (retryCount <= maxRetries) {
            long startTime = System.currentTimeMillis();
            try {
                ResponseEntity<String> response = restTemplate.exchange(chatCompletionsUrl, HttpMethod.POST, entity, String.class);
                long endTime = System.currentTimeMillis();
                System.out.println("API响应时间: " + (endTime - startTime) + "ms, 状态码: " + response.getStatusCode());
                
                // 检查响应状态
                if (response.getStatusCodeValue() >= 200 && response.getStatusCodeValue() < 300) {
                    System.out.println("响应体大小: " + (response.getBody() != null ? response.getBody().length() : 0) + " 字符");
                    return response;
                } else {
                    // 服务器返回了非成功状态码
                    System.err.println("API返回非成功状态码: " + response.getStatusCodeValue());
                    System.err.println("响应内容: " + response.getBody());
                    
                    if (retryCount >= maxRetries) {
                        throw new RuntimeException("API调用失败，状态码: " + response.getStatusCodeValue());
                    }
                }
            } catch (ResourceAccessException e) {
                // 网络相关异常，可以重试
                long endTime = System.currentTimeMillis();
                System.err.println("LLM API调用网络异常: " + e.getMessage());
                System.err.println("尝试次数: " + (retryCount + 1) + "/" + (maxRetries + 1));
                System.err.println("失败耗时: " + (endTime - startTime) + "ms");
                
                if (retryCount >= maxRetries) {
                    System.err.println("达到最大重试次数，放弃重试");
                    throw new RuntimeException("API调用网络异常，请检查网络连接和API服务状态: " + e.getMessage(), e);
                }
            } catch (Exception e) {
                long endTime = System.currentTimeMillis();
                System.err.println("LLM API调用失败: " + e.getMessage());
                System.err.println("失败耗时: " + (endTime - startTime) + "ms");
                System.err.println("API URL: " + chatCompletionsUrl);
                System.err.println("请求方法: POST");
                
                // 敏感信息不完全输出
                System.err.println("请求头: Content-Type=" + headers.getContentType());
                
                if (retryCount >= maxRetries) {
                    e.printStackTrace();
                    throw new RuntimeException("API调用失败，请检查配置和参数: " + e.getMessage(), e);
                }
            }
            
            // 增加重试延迟（指数退避）
            try {
                retryDelayMs *= 2; // 每次重试延迟时间翻倍
                System.out.println("等待 " + retryDelayMs + "ms 后重试...");
                Thread.sleep(retryDelayMs);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("重试过程被中断", ie);
            }
            
            retryCount++;
        }
        
        // 这里正常不会执行到，因为在最后一次重试失败后会抛出异常
        throw new RuntimeException("API调用失败，原因未知");
    }

    private List<Map<String, Object>> parseResponse(String responseBody) {
        System.out.println("解析API响应");
        
        if (responseBody == null || responseBody.isEmpty()) {
            System.err.println("API响应为空");
            return Collections.emptyList();
        }

        List<Map<String, Object>> requirements = new ArrayList<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(responseBody);
            
            // 检查API错误响应
            if (rootNode.has("error")) {
                JsonNode errorNode = rootNode.path("error");
                String errorType = errorNode.path("type").asText("unknown");
                String errorMessage = errorNode.path("message").asText("未知错误");
                System.err.println("API返回错误: " + errorType + " - " + errorMessage);
                
                // 创建一个错误需求项来保存错误信息
                Map<String, Object> errorRequirement = new HashMap<>();
                errorRequirement.put("name", "API错误");
                errorRequirement.put("content", "类型: " + errorType + "\n消息: " + errorMessage);
                errorRequirement.put("type", "text");
                requirements.add(errorRequirement);
                return requirements;
            }
            
            // 适配Moonshot API的响应格式
            JsonNode choicesNode = rootNode.path("choices");
            
            if (choicesNode.isArray() && choicesNode.size() > 0) {
                // 获取第一个选择的消息内容
                JsonNode messageNode = choicesNode.get(0).path("message");
                if (messageNode.isMissingNode()) {
                    System.err.println("响应格式错误：未找到message节点");
                    throw new RuntimeException("API响应格式不符合预期，未找到message节点");
                }
                
                String content = messageNode.path("content").asText("");
                if (content.isEmpty()) {
                    System.err.println("响应内容为空");
                    return Collections.emptyList();
                }
                
                System.out.println("提取的内容长度: " + content.length() + " 字符");

                // 尝试多种解析方式
                try {
                    // 尝试1: 直接解析JSON数组
                    if (content.startsWith("[") && content.endsWith("]")) {
                        try {
                            requirements = mapper.readValue(content, new TypeReference<List<Map<String, Object>>>() {});
                            System.out.println("成功解析为JSON数组，需求数量: " + requirements.size());
                            return requirements;
                        } catch (Exception e) {
                            System.out.println("JSON数组解析失败，尝试其他解析方式: " + e.getMessage());
                        }
                    }
                    
                    // 尝试2: 解析文本格式
                    requirements = parseTextResponse(content);
                    if (!requirements.isEmpty()) {
                        System.out.println("使用文本解析方法，需求数量: " + requirements.size());
                        return requirements;
                    } else {
                        System.out.println("文本解析方法未找到需求，使用默认方法");
                    }
                } catch (Exception e) {
                    System.out.println("所有解析方法都失败，尝试最后的备选方案: " + e.getMessage());
                }
                
                // 备选方案: 至少创建一个需求项
                Map<String, Object> defaultRequirement = new HashMap<>();
                defaultRequirement.put("name", "文档需求");
                defaultRequirement.put("content", content);
                defaultRequirement.put("type", "text");
                requirements.add(defaultRequirement);
                System.out.println("创建了默认需求项");
            } else {
                System.err.println("未找到choices节点或节点为空");
                System.err.println("原始响应: " + responseBody);
                throw new RuntimeException("API响应格式不符合预期，未找到choices节点或节点为空");
            }
        } catch (Exception e) {
            System.err.println("解析大模型响应失败：" + e.getMessage());
            e.printStackTrace();
            
            // 即使解析失败，也尝试创建一个包含原始响应的需求项
            try {
                Map<String, Object> fallbackRequirement = new HashMap<>();
                fallbackRequirement.put("name", "解析失败的响应");
                
                // 限制响应长度以避免过长
                String limitedResponse = responseBody;
                if (limitedResponse.length() > 1000) {
                    limitedResponse = limitedResponse.substring(0, 1000) + "... (截断)";
                }
                
                fallbackRequirement.put("content", "解析失败。原始响应: " + limitedResponse);
                fallbackRequirement.put("type", "text");
                requirements.add(fallbackRequirement);
            } catch (Exception ex) {
                // 最后的保底措施
                System.err.println("创建回退需求项也失败了: " + ex.getMessage());
            }
        }

        return requirements;
    }

    private List<Map<String, Object>> parseTextResponse(String content) {
        List<Map<String, Object>> requirements = new ArrayList<>();
        if (content == null || content.trim().isEmpty()) {
            return requirements;
        }

        String[] lines = content.split("\n");
        Map<String, Object> currentReq = null;
        boolean processingRequirement = false;

        // 预处理：检查是否有标准格式的需求
        boolean hasStandardFormat = false;
        for (String line : lines) {
            if (line.trim().matches("需求\\s*\\d+.*") || line.trim().matches(".*需求\\s*\\d+[:：].*")) {
                hasStandardFormat = true;
                break;
            }
        }

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            // 检测需求标题的多种可能格式
            boolean isNewRequirement = line.matches("需求\\s*\\d+.*") || 
                                      line.matches(".*需求\\s*\\d+[:：].*") ||
                                      (!hasStandardFormat && line.matches("\\d+\\.\\s+.*")) ||
                                      (!hasStandardFormat && line.matches("\\*\\s+.*") && line.length() < 100);

            if (isNewRequirement) {
                if (currentReq != null) {
                    requirements.add(currentReq);
                }
                currentReq = new HashMap<>();
                // 清理需求名称中的编号和特殊字符
                String name = line;
                name = name.replaceAll("^\\d+\\.\\s*", ""); // 移除前导数字和点
                name = name.replaceAll("^\\*\\s*", "");     // 移除前导星号
                name = name.replaceAll("^需求\\s*\\d+[：:]*\\s*", ""); // 移除"需求N："格式
                name = name.replaceAll("^.*需求\\s*\\d+[：:]*\\s*", ""); // 移除带前缀的需求格式
                
                currentReq.put("name", name);
                currentReq.put("content", "");
                currentReq.put("type", "text"); // 默认类型
                processingRequirement = true;
            } else if ((line.toLowerCase().startsWith("类型:") || line.startsWith("类型：") || 
                     line.toLowerCase().contains("类型:") || line.contains("类型：")) && currentReq != null) {
                // 提取类型信息
                String typeInfo = line;
                int typeIndex = Math.max(typeInfo.indexOf("类型:"), typeInfo.indexOf("类型："));
                if (typeIndex >= 0) {
                    typeInfo = typeInfo.substring(typeIndex + 3).trim();
                    
                    // 支持中文和英文的类型标识
                    String type = "text"; // 默认为文本类型
                    if (typeInfo.contains("文本") || typeInfo.toLowerCase().contains("text")) {
                        type = "text";
                    } else if (typeInfo.contains("数值") || typeInfo.toLowerCase().contains("num")) {
                        type = "num";
                    } else if (typeInfo.contains("选项") || typeInfo.toLowerCase().contains("option")) {
                        type = "option";
                    } else if (typeInfo.contains("范围") || typeInfo.toLowerCase().contains("range")) {
                        type = "range";
                    }
                    
                    currentReq.put("type", type);
                }
            } else if (currentReq != null) {
                // 添加到当前需求的内容中
                String contentValue = (String) currentReq.get("content");
                currentReq.put("content", contentValue + (contentValue.isEmpty() ? "" : "\n") + line);
            } else if (!processingRequirement) {
                // 如果还没有开始处理需求，并且遇到了一些文本，创建第一个需求
                currentReq = new HashMap<>();
                currentReq.put("name", "提取的需求");
                currentReq.put("content", line);
                currentReq.put("type", "text");
                processingRequirement = true;
            }
        }

        if (currentReq != null) {
            requirements.add(currentReq);
        }

        // 如果没有找到任何需求，但内容不为空，创建一个默认需求
        if (requirements.isEmpty() && !content.trim().isEmpty()) {
            Map<String, Object> defaultReq = new HashMap<>();
            defaultReq.put("name", "提取的文档内容");
            defaultReq.put("content", content);
            defaultReq.put("type", "text");
            requirements.add(defaultReq);
        }

        return requirements;
    }

    /**
     * 检查非标技术指标并生成风险评估报告
     * @param componentName 组件名称
     * @param standardCode 标准代码
     * @param indicators 技术指标列表
     * @return 风险评估报告
     */
    public Map<String, Object> checkNonStandardIndicators(String componentName, String standardCode, List<Map<String, Object>> indicators) {
        if (componentName == null || componentName.isEmpty()) {
            throw new IllegalArgumentException("组件名称不能为空");
        }
        
        if (standardCode == null || standardCode.isEmpty()) {
            throw new IllegalArgumentException("标准代码不能为空");
        }
        
        if (indicators == null || indicators.isEmpty()) {
            throw new IllegalArgumentException("技术指标列表不能为空");
        }
        
        System.out.println("开始检查非标技术指标，组件：" + componentName + "，标准：" + standardCode + "，指标数量：" + indicators.size());
        
        try {
            // 构建提示词
            StringBuilder prompt = new StringBuilder();
            prompt.append("你是一个高速列车技术指标审核专家。请根据标准 ");
            prompt.append(standardCode);
            prompt.append(" 审核以下高速列车组件 \"");
            prompt.append(componentName);
            prompt.append("\" 的技术指标，并判断这些指标是否在该标准中存在。\n\n");
            prompt.append("以下是需要审核的技术指标：\n");
            
            // 添加所有技术指标信息
            for (int i = 0; i < indicators.size(); i++) {
                Map<String, Object> indicator = indicators.get(i);
                prompt.append(i + 1).append(". 指标名称：").append(indicator.get("name")).append("\n");
                prompt.append("   指标类型：").append(getIndicatorTypeName(indicator.get("type").toString())).append("\n");
                prompt.append("\n");
            }
            
            // 添加要求
            prompt.append("请执行以下任务：\n");
            prompt.append("1. 对于每个技术指标，判断其是否在 ").append(standardCode).append(" 标准中存在\n");
            prompt.append("2. 如果指标在标准中存在，标记为'符合标准'，否则标记为'非标指标'\n");
            prompt.append("3. 对于非标指标，评估其风险级别（高风险/中风险/低风险）\n");
            prompt.append("4. 对于每个非标指标，说明为什么它不符合标准，以及可能带来的风险\n");
            prompt.append("5. 给出整体风险评估结果\n\n");
            
            prompt.append("请按以下JSON格式回复，不要添加任何其他内容：\n");
            prompt.append("{\n");
            prompt.append("  \"overallRisk\": \"high/medium/low/safe\",\n");
            prompt.append("  \"details\": [\n");
            prompt.append("    {\n");
            prompt.append("      \"name\": \"指标名称\",\n");
            prompt.append("      \"existsInStandard\": true/false,\n");
            prompt.append("      \"standardRequirement\": \"标准中的相关内容（如存在）\",\n");
            prompt.append("      \"riskLevel\": \"high/medium/low/safe\",\n");
            prompt.append("      \"analysis\": \"分析内容，说明指标是否在标准中，以及可能的风险\"\n");
            prompt.append("    }\n");
            prompt.append("  ],\n");
            prompt.append("  \"suggestions\": [\"建议1\", \"建议2\"]\n");
            prompt.append("}\n");
            
            System.out.println("提示词构建完成，长度：" + prompt.length() + " 字符");
            
            // 构建API请求
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "moonshot-v1-32k");
            
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个高速列车技术指标专家，熟悉各种高速列车相关标准，能够对技术指标进行准确评估。");
            
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", prompt.toString());
            
            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            
            // 添加其他参数
            requestBody.put("temperature", 0.2); // 使用较低温度以获得更确定性的回答
            requestBody.put("top_p", 0.95);
            requestBody.put("stream", false);
            requestBody.put("max_tokens", 4000);
            
            System.out.println("请求体构建完成，开始调用API");
            ResponseEntity<String> response = callLlmApi(requestBody);
            System.out.println("API调用完成，解析响应");
            
            // 解析响应并构建风险评估报告
            Map<String, Object> report = parseNonStandardIndicatorsResponse(response.getBody());
            
            // 添加基本信息
            report.put("checkTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            report.put("standard", standardCode);
            report.put("componentName", componentName);
            
            System.out.println("非标技术指标检查完成，风险级别：" + report.get("overallRisk"));
            return report;
        } catch (ResourceAccessException e) {
            System.err.println("API连接超时或网络错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("API请求超时，请稍后重试: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("检查非标技术指标过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("检查非标技术指标失败: " + e.getMessage());
        }
    }
    
    /**
     * 将技术指标类型代码转换为中文名称
     */
    private String getIndicatorTypeName(String typeCode) {
        switch (typeCode) {
            case "text": return "文本";
            case "num": return "数值";
            case "range": return "范围";
            case "option": return "选项";
            default: return typeCode;
        }
    }
    
    /**
     * 解析非标技术指标检查响应
     */
    private Map<String, Object> parseNonStandardIndicatorsResponse(String responseBody) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> result = new HashMap<>();
            
            // 解析JSON响应
            JsonNode rootNode = mapper.readTree(responseBody);
            JsonNode choicesNode = rootNode.path("choices");
            
            if (choicesNode.isArray() && choicesNode.size() > 0) {
                // 获取第一个选择的消息内容
                JsonNode messageNode = choicesNode.get(0).path("message");
                if (messageNode.isMissingNode()) {
                    System.err.println("响应格式错误：未找到message节点");
                    throw new RuntimeException("API响应格式不符合预期，未找到message节点");
                }
                
                String content = messageNode.path("content").asText("");
                if (content.isEmpty()) {
                    System.err.println("响应内容为空");
                    return createDefaultReport();
                }
                
                System.out.println("提取的内容长度: " + content.length() + " 字符");
                
                // 尝试从内容中提取JSON
                int startIdx = content.indexOf('{');
                int endIdx = content.lastIndexOf('}');
                
                if (startIdx >= 0 && endIdx > startIdx) {
                    String jsonContent = content.substring(startIdx, endIdx + 1);
                    try {
                        // 解析JSON内容
                        JsonNode reportNode = mapper.readTree(jsonContent);
                        
                        // 提取整体风险级别
                        String overallRisk = reportNode.path("overallRisk").asText("medium");
                        result.put("overallRisk", overallRisk);
                        
                        // 提取详细信息
                        JsonNode detailsNode = reportNode.path("details");
                        if (detailsNode.isArray()) {
                            List<Map<String, Object>> details = new ArrayList<>();
                            for (JsonNode detailNode : detailsNode) {
                                Map<String, Object> detail = new HashMap<>();
                                detail.put("name", detailNode.path("name").asText(""));
                                detail.put("existsInStandard", detailNode.path("existsInStandard").asBoolean(false));
                                detail.put("standardRequirement", detailNode.path("standardRequirement").asText(""));
                                detail.put("riskLevel", detailNode.path("riskLevel").asText("medium"));
                                detail.put("analysis", detailNode.path("analysis").asText(""));
                                details.add(detail);
                            }
                            result.put("details", details);
                        } else {
                            result.put("details", new ArrayList<>());
                        }
                        
                        // 提取建议
                        JsonNode suggestionsNode = reportNode.path("suggestions");
                        if (suggestionsNode.isArray()) {
                            List<String> suggestions = new ArrayList<>();
                            for (JsonNode suggestionNode : suggestionsNode) {
                                suggestions.add(suggestionNode.asText(""));
                            }
                            result.put("suggestions", suggestions);
                        } else {
                            result.put("suggestions", new ArrayList<>());
                        }
                        
                        return result;
                    } catch (Exception e) {
                        System.err.println("解析JSON内容失败: " + e.getMessage());
                        System.err.println("尝试从文本中提取有用信息");
                    }
                }
                
                // 如果JSON解析失败，尝试从文本中提取有用信息
                return extractReportFromText(content);
            }
            
            System.err.println("未找到有效的响应选择");
            return createDefaultReport();
        } catch (Exception e) {
            System.err.println("解析响应过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return createDefaultReport();
        }
    }
    
    /**
     * 从文本中提取报告信息
     */
    private Map<String, Object> extractReportFromText(String content) {
        Map<String, Object> result = new HashMap<>();
        
        // 默认风险级别
        String overallRisk = "medium";
        
        // 尝试确定整体风险级别
        if (content.contains("高风险") || content.contains("严重不符合")) {
            overallRisk = "high";
        } else if (content.contains("中风险") || content.contains("部分不符合")) {
            overallRisk = "medium";
        } else if (content.contains("低风险") || content.contains("基本符合")) {
            overallRisk = "low";
        } else if (content.contains("符合标准") || content.contains("无风险")) {
            overallRisk = "safe";
        }
        
        result.put("overallRisk", overallRisk);
        
        // 简单提取建议
        List<String> suggestions = new ArrayList<>();
        if (overallRisk.equals("high")) {
            suggestions.add("建议立即对高风险指标进行调整，以符合相关标准要求。");
            suggestions.add("进行全面技术评审，确保所有组件符合行业标准。");
        } else if (overallRisk.equals("medium")) {
            suggestions.add("建议对标识为中等风险的技术指标进行优先调整。");
            suggestions.add("定期监控这些指标，确保其不会恶化到高风险级别。");
        } else {
            suggestions.add("继续保持良好状态，定期检查以确保持续符合标准要求。");
        }
        
        result.put("suggestions", suggestions);
        result.put("details", new ArrayList<>());
        
        return result;
    }
    
    /**
     * 创建默认报告
     */
    private Map<String, Object> createDefaultReport() {
        Map<String, Object> result = new HashMap<>();
        result.put("overallRisk", "medium");
        result.put("details", new ArrayList<>());
        result.put("suggestions", Arrays.asList("由于无法生成详细评估，建议进行人工审核。"));
        return result;
    }

    /**
     * 上传自定义企业标准文档（直接使用文本内容）
     * @param standardName 标准名称
     * @param content 标准文本内容
     * @return 自定义标准对象
     */
    public CustomStandard uploadCustomStandardText(String standardName, String content) throws Exception {
        if (content == null || content.isEmpty()) {
            throw new IllegalArgumentException("标准文档内容不能为空");
        }
        
        // 1. 生成唯一ID
        String standardId = UUID.randomUUID().toString();
        
        // 2. 创建自定义标准对象
        CustomStandard standard = new CustomStandard();
        standard.setId(standardId);
        standard.setName(standardName);
        standard.setContent(content);
        standard.setUploadTime(new Date());
        standard.setStatus("ACTIVE");
        
        // 3. 存储自定义标准
        customStandardsStorage.put(standardId, standard);
        
        System.out.println("成功上传自定义企业标准，ID: " + standardId + ", 名称: " + standardName);
        return standard;
    }

    /**
     * 自定义标准类
     */
    public static class CustomStandard {
        private String id;
        private String name;
        private String content;
        private Date uploadTime;
        private String status;
        private List<StandardRequirement> requirements;
        
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public Date getUploadTime() { return uploadTime; }
        public void setUploadTime(Date uploadTime) { this.uploadTime = uploadTime; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public List<StandardRequirement> getRequirements() { return requirements; }
        public void setRequirements(List<StandardRequirement> requirements) { this.requirements = requirements; }
    }
    
    /**
     * 标准要求类
     */
    public static class StandardRequirement {
        private String id;
        private String name;
        private String content;
        
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }

    /**
     * 从文本内容提取标准要求
     */
    private List<StandardRequirement> extractStandardRequirements(String content) throws Exception {
        // 构建提示词
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个标准文档解析专家。请从以下标准文档中提取关键的技术指标要求。");
        prompt.append("对每个指标要求，提供以下信息：1. 指标名称，2. 要求内容\n\n");
        prompt.append(content);
        
        // 调用LLM API
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "moonshot-v1-32k");
        
        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个专业的技术标准解析专家，擅长从标准文档中提取关键技术指标要求。请以JSON格式输出结果。");
        
        Map<String, Object> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", prompt.toString());
        
        messages.add(systemMessage);
        messages.add(userMessage);
        requestBody.put("messages", messages);
        
        // 添加其他参数
        requestBody.put("temperature", 0.3);
        requestBody.put("top_p", 0.95);
        requestBody.put("stream", false);
        requestBody.put("max_tokens", 3000);
        
        ResponseEntity<String> response = callLlmApi(requestBody);
        
        // 解析响应
        List<StandardRequirement> requirements = new ArrayList<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(response.getBody());
            JsonNode choicesNode = rootNode.path("choices");
            
            if (choicesNode.isArray() && choicesNode.size() > 0) {
                String contentText = choicesNode.get(0).path("message").path("content").asText("");
                
                // 尝试从内容中提取JSON
                int startIdx = contentText.indexOf('[');
                int endIdx = contentText.lastIndexOf(']');
                
                if (startIdx >= 0 && endIdx > startIdx) {
                    String jsonContent = contentText.substring(startIdx, endIdx + 1);
                    
                    // 解析JSON数组
                    JsonNode requirementsNode = mapper.readTree(jsonContent);
                    for (JsonNode reqNode : requirementsNode) {
                        StandardRequirement req = new StandardRequirement();
                        req.setId(UUID.randomUUID().toString());
                        req.setName(reqNode.path("name").asText(""));
                        req.setContent(reqNode.path("content").asText(""));
                        requirements.add(req);
                    }
                } else {
                    // 如果没有找到JSON数组，尝试从文本中提取要求
                    requirements = extractRequirementsFromText(contentText);
                }
            }
        } catch (Exception e) {
            System.err.println("解析提取的标准要求失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return requirements;
    }
    
    /**
     * 从文本中提取标准要求
     */
    private List<StandardRequirement> extractRequirementsFromText(String text) {
        List<StandardRequirement> requirements = new ArrayList<>();
        String[] lines = text.split("\n");
        
        StandardRequirement currentReq = null;
        
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;
            
            if (line.matches("\\d+\\..*") || line.matches("第.*[条章节].*") || line.startsWith("•") || line.startsWith("*")) {
                // 开始新的要求
                if (currentReq != null && !currentReq.getName().isEmpty()) {
                    requirements.add(currentReq);
                }
                
                currentReq = new StandardRequirement();
                currentReq.setId(UUID.randomUUID().toString());
                
                // 清理行文本
                String name = line.replaceAll("^\\d+\\.\\s*", "")
                                .replaceAll("^第.*[条章节]\\s*", "")
                                .replaceAll("^[•*]\\s*", "");
                
                // 限制名称长度
                if (name.length() > 100) {
                    name = name.substring(0, 100) + "...";
                }
                
                currentReq.setName(name);
                currentReq.setContent(line);
            } else if (currentReq != null) {
                // 追加到当前要求内容
                currentReq.setContent(currentReq.getContent() + "\n" + line);
            }
        }
        
        // 添加最后一个要求
        if (currentReq != null && !currentReq.getName().isEmpty()) {
            requirements.add(currentReq);
        }
        
        return requirements;
    }

    /**
     * 使用自定义标准检查技术指标
     * @param componentName 组件名称
     * @param standardId 自定义标准ID
     * @param indicators 技术指标列表
     * @return 风险评估报告
     */
    public Map<String, Object> checkWithCustomStandard(String componentName, String standardId, List<Map<String, Object>> indicators) {
        if (componentName == null || componentName.isEmpty()) {
            throw new IllegalArgumentException("组件名称不能为空");
        }
        
        if (standardId == null || standardId.isEmpty()) {
            throw new IllegalArgumentException("标准ID不能为空");
        }
        
        if (indicators == null || indicators.isEmpty()) {
            throw new IllegalArgumentException("技术指标列表不能为空");
        }
        
        // 获取自定义标准
        CustomStandard standard = customStandardsStorage.get(standardId);
        if (standard == null) {
            throw new IllegalArgumentException("找不到指定的自定义标准");
        }
        
        System.out.println("开始使用自定义标准检查技术指标，组件：" + componentName + "，标准：" + standard.getName());
        
        try {
            // 构建提示词
            StringBuilder prompt = new StringBuilder();
            prompt.append("你是一个高速列车技术指标审核专家。请根据以下自定义企业标准文档审核高速列车组件 \"");
            prompt.append(componentName);
            prompt.append("\" 的技术指标，并判断这些指标是否在该标准中存在。\n\n");
            prompt.append("以下是企业标准文档内容：\n");
            prompt.append(standard.getContent());
            prompt.append("\n\n");
            
            prompt.append("以下是需要审核的技术指标：\n");
            
            // 添加所有技术指标信息
            for (int i = 0; i < indicators.size(); i++) {
                Map<String, Object> indicator = indicators.get(i);
                prompt.append(i + 1).append(". 指标名称：").append(indicator.get("name")).append("\n");
                
                // 添加指标值信息
                if (indicator.get("value") != null) {
                    Object value = indicator.get("value");
                    if (value instanceof List) {
                        List<?> valueList = (List<?>) value;
                        prompt.append("   指标值：").append(String.join(", ", valueList.stream().map(Object::toString).toArray(String[]::new))).append("\n");
                    } else {
                        prompt.append("   指标值：").append(value).append("\n");
                    }
                }
                
                prompt.append("\n");
            }
            
            // 添加要求
            prompt.append("请执行以下任务：\n");
            prompt.append("1. 对于每个技术指标，判断其是否在企业标准文档中存在或有相关规定\n");
            prompt.append("2. 如果指标在标准中存在，标记为'符合标准'，否则标记为'非标指标'\n");
            prompt.append("3. 对于非标指标，评估其风险级别（高风险/中风险/低风险）\n");
            prompt.append("4. 对于每个非标指标，说明为什么它不符合标准，以及可能带来的风险\n");
            prompt.append("5. 给出整体风险评估结果\n\n");
            
            prompt.append("请按以下JSON格式回复，不要添加任何其他内容：\n");
            prompt.append("{\n");
            prompt.append("  \"overallRisk\": \"high/medium/low/safe\",\n");
            prompt.append("  \"details\": [\n");
            prompt.append("    {\n");
            prompt.append("      \"name\": \"指标名称\",\n");
            prompt.append("      \"existsInStandard\": true/false,\n");
            prompt.append("      \"standardRequirement\": \"标准中的相关内容（如存在）\",\n");
            prompt.append("      \"riskLevel\": \"high/medium/low/safe\",\n");
            prompt.append("      \"analysis\": \"分析内容，说明指标是否在标准中，以及可能的风险\"\n");
            prompt.append("    }\n");
            prompt.append("  ],\n");
            prompt.append("  \"suggestions\": [\"建议1\", \"建议2\"]\n");
            prompt.append("}\n");
            
            // 构建API请求
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "moonshot-v1-32k");
            
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个高速列车技术指标专家，能够根据提供的企业标准文档对技术指标进行准确评估。");
            
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", prompt.toString());
            
            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            
            // 添加其他参数
            requestBody.put("temperature", 0.2);
            requestBody.put("top_p", 0.95);
            requestBody.put("stream", false);
            requestBody.put("max_tokens", 4000);
            
            System.out.println("请求体构建完成，开始调用API");
            ResponseEntity<String> response = callLlmApi(requestBody);
            System.out.println("API调用完成，解析响应");
            
            // 解析响应并构建风险评估报告
            Map<String, Object> report = parseNonStandardIndicatorsResponse(response.getBody());
            
            // 添加基本信息
            report.put("checkTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            report.put("standard", standard.getName() + " (自定义标准)");
            report.put("standardId", standard.getId());
            report.put("componentName", componentName);
            
            System.out.println("自定义标准技术指标检查完成，风险级别：" + report.get("overallRisk"));
            return report;
        } catch (Exception e) {
            System.err.println("检查自定义标准技术指标过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("检查自定义标准技术指标失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取自定义标准
     */
    public CustomStandard getCustomStandardById(String standardId) {
        return customStandardsStorage.get(standardId);
    }
    
    /**
     * 获取所有自定义标准
     */
    public List<CustomStandard> getAllCustomStandards() {
        return new ArrayList<>(customStandardsStorage.values());
    }
}